package com.offcn.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.offcn.entity.Book;
import com.offcn.entity.ResultVo;
import com.offcn.service.BookService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/bookServlet")
public class BookServlet extends HttpServlet {
    //利用Java反射机制构建一个通用执行各个方法的service方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodName = req.getParameter("methodName");
        Class clazz = this.getClass();
        Method m = null;
        try {
            m = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            m.invoke(this, req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //提升作用域，让每个方法都能使用
    BookService service = new BookService();

    //查询所有图书的方法
    public void queryAllBooks(HttpServletRequest req,HttpServletResponse resp) throws IOException, SQLException {
        List<Book> list = service.queryAllBooks();
        ResultVo resultVo;
        if (list != null && list.size() > 0){
            resultVo = new ResultVo(1, "查询成功！", list);
        }else {
            resultVo = new ResultVo(0, "查询失败！", list);
        }
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(resultVo);
        System.out.println(s);
        resp.getWriter().print(s);
    }




}
